﻿using Prism.Services.Dialogs;
using SmartParking.Base;
using SmartParking.Entities;
using SmartParking.IService;
using SmartParking.Models;
using System.Net;
using System.Windows;
using System.Windows.Controls;

namespace SmartParking.ViewModels.Pages.Dialogs
{
    public class ModifyUserViewModel : DialogViewModelBase
    {
        public UserModel User { get; set; } = new();

        public bool IsReadOnly { get; set; }

        IUserService _userService;

        public ModifyUserViewModel(IUserService userService)
        {
            _userService = userService;
        }

        public override void OnDialogOpened(IDialogParameters parameters)
        {
            var model = parameters.GetValue<UserModel>("model");
            if (model == null)
            {
                Title = "新建用户";

            }
            else
            {
                Title = "修改用户";
                IsReadOnly = true;
            }
        }

        public override void DoSave()
        {
            try
            {
                if (User.UserId == 0)
                {
                    _userService.Insert(new SysUser
                    {
                        UserName = User.UserName,
                        RealName = User.RealName,
                        Password = User.Password,
                        Address = User.Address,
                        Age = User.Age,
                        CreateTime = DateTime.Now,
                        CreateId = 1,
                        LastModifyTime = DateTime.Now,
                        LastModifyId = 1,
                        Phone = User.Phone,
                        Email = User.Email,
                    });
                }
                else
                {
                    var user = _userService.Find<SysUser>(User.UserId);

                    user.Address = User.Address;
                    user.Age = User.Age;
                    user.LastModifyTime = DateTime.Now;
                    user.LastModifyId = 1;
                    user.Phone = User.Phone;
                    user.Email = User.Email;

                    _userService.Update(user);
                }

                base.DoSave();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


    }
}
